package com.totobox.apps.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.DBHelper;
import com.totobox.apps.common.ImageDownloader;
import com.totobox.apps.common.MoveActivity;
import com.totobox.apps.common.SortCustomDialog;
import com.totobox.apps.common.Util;

public class MyStorageActivity extends BasicActivity {
	enum BUTTON {PLAY_CHANGE, SORT, DELETE_CHANGE, PLAY, DELETE, ALL_SELECT, CANCEL};
	
	private ProgressDialog progressDialog;
	final public int PROGRESS_DIALOG = 0;
	final public int SORT_DIALOG = 1;	//정렬 알럿창
	
	public Thread dataThread = null;
	public Handler handler = new Handler();
	
	public ListView listView;
	public ListAdapter listAdapter;
	
	//체크 박스 리스트
	public List<CheckBox> checkList = new ArrayList<CheckBox>();
	
	public LinearLayout menu_footer;
	
	//전체 선택 여부
	public boolean isAllCheck = true;
	
	//체크박스 visible 여부
	public boolean isVisible = false;
	
	public ImageButton btn_all;
	public ImageButton btn_sort;
	public ImageButton btn_delete;
	public ImageButton btn_delete_change;
	public ImageButton btn_play_change;
	public ImageButton btn_cancel;
	public ImageButton btn_play;
	
	DBHelper mHelper;
	public SQLiteDatabase db;
	private int folderType = 0, page = 0, totalPage = 0;
	
	Map<String,String> result = null;
	List<Map<String,String>> downloadList = new ArrayList<Map<String,String>>();
	
	public List<ImageView> imageList = new ArrayList<ImageView>();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.my_storage);
        
        //초기화
        checkList.clear();
        
        listView = (ListView)findViewById(R.id.download_list);
        listView.setOnItemClickListener(this);
        
        menu_footer = (LinearLayout)findViewById(R.id.menu_footer);
        
        super.initTitle();
        
        //상단 메뉴
        super.showTopMenu(MyStorageActivity.this);
        
        //하단 메뉴 세팅
        super.setFooterMenu(this);
        
        //하단 down 메뉴
        this.ListFooterMenu(BUTTON.CANCEL);
        
        showDialog(PROGRESS_DIALOG);
        
        mHelper = new DBHelper(this);
    	db=mHelper.getWritableDatabase();
    	
    	if (Const.MENU.equals("IMG"))
    		folderType = 1;
    	else if (Const.MENU.equals("VOD"))
    		folderType = 2;
    	else if (Const.MENU.equals("AUD"))
    		folderType = 3;
    	else if (Const.MENU.equals("ETC"))
    		folderType = 4;
		
		dataThread = new Thread(null, sqliteList);
    	dataThread.start();
    }

	@Override
	public void onClick(View v) {
		if(v == btn_all){
			this.setAllChecked();
		}
		else if (v == btn_sort){
			showDialog(SORT_DIALOG);
		}
		else if (v == btn_delete){
			this.fileListDelete();
		}
		else if (v == btn_play) {
			int chkCnt = 0;
			if(checkList != null && !checkList.isEmpty()){
				int size = checkList.size();
				
				Const.dnQueue.clear();
				
				for(int i = 0 ; i < size ; i++){
					if(checkList.get(i).isChecked()){
						
						//체크된 다운 파일을 선별한다.
						Const.dnQueue.add(downloadList.get(checkList.get(i).getId()));
						chkCnt++;
					}
				}
			}
			
			if(chkCnt == 0){
				showText(2);
				return;
			}
			
			if(folderType == 2){		//동영상 일경우 알럿을 띄운다
				MoveActivity go = new MoveActivity(MyStorageActivity.this , TotoVodPlayerActivity.class);
				go.startActivity();	
			}
			else if(folderType == 1){		//이미지 보기 
				MoveActivity go = new MoveActivity(MyStorageActivity.this , TotoPhotoViewActivity.class);
				go.startActivity();		
			}
			else if(folderType == 3){		//음악 플레이
				MoveActivity go = new MoveActivity(MyStorageActivity.this , TotoMusicPlayerActivity.class);
				go.startActivity();
			}
			else if(folderType == 4){		//기타
				MoveActivity go = new MoveActivity(MyStorageActivity.this , TotoFileConfirmActivity.class);
				go.startActivity();
			}
		}
		else if (v == btn_delete_change){
			isVisible = true;
			this.setClickable(true);
			this.ListFooterMenu(BUTTON.DELETE_CHANGE);
		}
		else if (v == btn_play_change){
			isVisible = true;
			this.setClickable(true);
			this.ListFooterMenu(BUTTON.PLAY_CHANGE);
		}
		else if (v == btn_cancel){
			isVisible = false;
			this.setClickable(false);
			this.ListFooterMenu(BUTTON.CANCEL);
			this.setCanceled();
		}
	}
    
	/**
	 * 북마크 리스트
	 */
	private Runnable sqliteList = new Runnable() {
    	public void run() {
    		try {
    			String[] bind1 = {folderType+""};
    			Cursor cursor = db.rawQuery("select count(*) totCount from download where iFolderType = ?", bind1);
    	    	cursor.moveToFirst();
    	    	
    	    	totalPage = cursor.getInt(0);
    	    	cursor.close();
    	    	
    	    	String[] bind2 = {folderType+"", Const.sortName , page+""};
    	    	cursor = db.rawQuery("select biFileSeq, iFileType, vcName, vcFileKey, iFileSize, vcFilePlayTime, vcFilePath, dtRegDate from download where iFolderType = ? order by ? limit ?, 25", bind2);
    	    	startManagingCursor(cursor);
    	    	
    	    	cursor.moveToFirst();
    	    	 
    	    	while (!cursor.isAfterLast()){
    	    	   	result = new HashMap<String, String>();
    	    	   	result.put("biFileSeq", cursor.getInt(0)+"");
   					result.put("iFileType", cursor.getInt(1)+"");
   					result.put("vcName", cursor.getString(2)+"");
   					result.put("vcFileKey", cursor.getString(3));
   					result.put("iFileSize", cursor.getInt(4)+"");
   					result.put("vcFilePlayTime", cursor.getInt(5)+"");
   					result.put("vcFilePath", cursor.getString(6));
   					result.put("dtRegDate", cursor.getString(7));
   					
   					downloadList.add(result);
   				
   					cursor.moveToNext();
    	    	}
    	    	cursor.close();
    	    	
		    	handler.post(dataResults);
		    	
    		} catch (Exception e) {
    			Log.d("partData : ", e.toString());
    		}
    	}
    };
    
    /**
     * 
     */
	private Runnable dataResults = new Runnable() {
    	public void run() {
    		try {
    			if (downloadList != null) {
    				
    				listAdapter = new ListAdapter(MyStorageActivity.this, R.layout.item_folder_list, downloadList);
    				listView.setAdapter(listAdapter);
    				
    			}
    			else{
    				showText(1);
    			}
    			
    	    	progressDialog.dismiss();
    	    	MyStorageActivity.this.removeDialog(PROGRESS_DIALOG);
    	    	
    		} catch (Exception e) {
    			Log.e("sqlite", e.toString());
    		}

    	}
    };
    
    private void showText(int showType) {
    	switch (showType) {
		case 1:
			super.showText(this, "다운로 리스트가 없습니다.", Toast.LENGTH_SHORT);
			break;

		case 2:
			super.showText(this, "선택된 파일이 없습니다.", Toast.LENGTH_SHORT);
	    	break;
	    	
		case 3:
			super.showText(this, "선택된 파일이 완전 삭제되었습니다.", Toast.LENGTH_SHORT);
	    	break;
	    	
		default:
			break;
		}
    }
    
    class ListAdapter extends ArrayAdapter {
    	
    	private int layout;
    	private Activity context;
    	List<Map<String,String>> list;
    	
    	private final ImageDownloader imageDownloader = new ImageDownloader();
    	
    	@SuppressWarnings("unchecked")
    	public ListAdapter(Activity context , int layout , List<Map<String,String>> list){
    		
    		super(context , layout , list);
    		
    		this.context = context;
    		this.list = list;
    		this.layout = layout;
    	}
    	
    	public View getView(int position , View convertView , ViewGroup parent){
    		
    		Map<String,String> map = list.get(position);
    		
    		LayoutInflater inflater = context.getLayoutInflater();
    		View view = inflater.inflate(layout, null);
    		
    		CheckBox file_check = (CheckBox)view.findViewById(R.id.file_check);
    		file_check.setId(position);
    		if (isVisible)
    			file_check.setVisibility(View.VISIBLE);
    		else
    			file_check.setVisibility(View.INVISIBLE);
    		
    		ImageView list_icon = (ImageView)view.findViewById(R.id.list_icon);
    		TextView txt_list_name = (TextView)view.findViewById(R.id.txt_list_name);
    		TextView txt_detail = (TextView)view.findViewById(R.id.txt_detail);
    		txt_list_name.setText(map.get("vcName"));
    		
    		
    		checkList.add(file_check);
    		imageList.add(list_icon);
			file_check.setFocusable(false);
			file_check.setClickable(false);
			int fileSize = Integer.parseInt(map.get("iFileSize"))/1024/1024;
			int playTime = Integer.parseInt(map.get("vcFilePlayTime"));
			
			txt_detail.setText(map.get("dtRegDate") + "  " + fileSize + "MB " + playTime/60/60 + ":" + playTime/60%60 + ":" + playTime%60);
			
			
			if (folderType == 1) {//다운로드 받은 이미지를 보여준다
				
		    }
		    else { //각각 디폴트 이미지
		    	list_icon.setImageDrawable(getResources().getDrawable(R.drawable.movie_btn));
		    }
    		
    		return  view;
    	}
    }
    
    
	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		
		Map<String,String> map = downloadList.get(position);
		
		Intent intent = new Intent(MyStorageActivity.this , TotoPhotoViewActivity.class);
		intent.putExtra("position", Util.stringToInt(map.get(position+""),0));
		startActivity(intent);
	}
	
	/**
	 * 체크 박스 체크 가능 상태 변경
	 * @param isAble
	 */
	public void setClickable(boolean isAble){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setClickable(isAble);
				if (isAble)
					checkList.get(i).setVisibility(View.VISIBLE);
				else
					checkList.get(i).setVisibility(View.INVISIBLE);
			}
		}
	}
	
	/**
	 * 전체 체크
	 * @param isAble
	 */
	public void setAllChecked(){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setChecked(isAllCheck);
			}
		}
		
		//현재의 반대를 넣는다.
		isAllCheck = !isAllCheck;
		
		if (isAllCheck)
			btn_all.setBackgroundDrawable(getResources().getDrawable(R.drawable.allselect_off));
		else
			btn_all.setBackgroundDrawable(getResources().getDrawable(R.drawable.allselect_on));
	}
	
	/**
	 * 전체 체크 해제
	 * @param isAble
	 */
	public void setCanceled(){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setChecked(false);
				
			}
		}
	}
	
	public void fileListDelete() {
		if (checkList.size() == 0) {
			showText(2);
	        return;
	    }
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("알림");
		dialog.setMessage("선택된 파일을 삭제하시겠습니까?");
		dialog.setPositiveButton("예", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try{
					db.beginTransaction();
					for(int i = 0 ; i < checkList.size() ; i++){
						
						if (checkList.get(i).isChecked()) {
							Map<String,String> map = downloadList.get(checkList.get(i).getId());
							String[] bind = {map.get("biFileSeq")};
							db.delete("download", "biFileSeq = ?", bind);
						}
						
					}
					db.setTransactionSuccessful();
				} catch (SQLException e){
				} finally {
					db.endTransaction();
				}
				db.beginTransaction();
				
				for(int i = 0 ; i < checkList.size() ; i++){
					
					if (checkList.get(i).isChecked()) {
						downloadList.remove(checkList.get(i).getId());
						checkList.remove(i);
						i--;
					}
					
				}
				
				showText(3);
				listAdapter.notifyDataSetChanged();
			}
		});
		
		dialog.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		dialog.show();
	}

	@Override
	protected Dialog onCreateDialog (int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("목록 로딩중 입니다.");
			return progressDialog;
			
		case SORT_DIALOG:
			
			Dialog dialog = new SortCustomDialog(this);
    		dialog.show();
			
			return null;
		default:
			
			return null;
		}
	}
	
	//------------------------------------- 하단 play, 정렬, 삭제 메뉴 구성-------------------------------
	public void ListFooterMenu(BUTTON en){
		View v = null;
		
		//기존에 가지고 있던 뷰 제거
		if(menu_footer != null && menu_footer.getChildCount() >0) menu_footer.removeAllViews();
		
		//새로운 뷰를 추가 
		LayoutInflater inflater = this.getLayoutInflater();
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(3, ViewGroup.LayoutParams.WRAP_CONTENT,0.0F);
		LinearLayout linear = new LinearLayout(this);
		linear.setLayoutParams(params);
		
		if (en.ordinal() >= 6) {
			btn_play_change = new ImageButton(this);
			btn_play_change.setBackgroundDrawable(getResources().getDrawable(R.drawable.smbtn_play_nomal));
			btn_play_change.setOnClickListener(this);
			menu_footer.addView(btn_play_change);
			
			menu_footer.addView(linear);
			
			btn_sort = new ImageButton(this);
			btn_sort.setBackgroundDrawable(getResources().getDrawable(R.drawable.smbtn_reflash_nomal));
			btn_sort.setOnClickListener(this);
			menu_footer.addView(btn_sort);
			
			menu_footer.addView(linear);
			
			btn_delete_change = new ImageButton(this);
			btn_delete_change.setBackgroundDrawable(getResources().getDrawable(R.drawable.smbtn_del_nomal));
			btn_delete_change.setOnClickListener(this);
			menu_footer.addView(btn_delete_change);
		}
		else {
			if (en.ordinal() == 0) {
				btn_all = new ImageButton(this);
				btn_all.setBackgroundDrawable(getResources().getDrawable(R.drawable.allselect_off));
				btn_all.setOnClickListener(this);
				menu_footer.addView(btn_all);
				
				menu_footer.addView(linear);
				
				btn_play = new ImageButton(this);
				btn_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.smbtn_play_nomal));
				btn_play.setOnClickListener(this);
				menu_footer.addView(btn_play);
			}
			else {
				btn_all = new ImageButton(this);
				btn_all.setBackgroundDrawable(getResources().getDrawable(R.drawable.allselect_off));
				btn_all.setOnClickListener(this);
				menu_footer.addView(btn_all);
				
				menu_footer.addView(linear);
				
				btn_delete = new ImageButton(this);
				btn_delete.setBackgroundDrawable(getResources().getDrawable(R.drawable.smbtn_del_nomal));
				btn_delete.setOnClickListener(this);
				menu_footer.addView(btn_delete);
				menu_footer.addView(linear);
			}
			
			btn_cancel = new ImageButton(this);
			btn_cancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.cancel_off));
			btn_cancel.setOnClickListener(this);
			menu_footer.addView(btn_cancel);
		}
	}
	//-------------------------------------------------------------------------------------

	@Override
    protected void onDestroy() {
		db.close();
		
		try{
			if(imageList != null && !imageList.isEmpty()){
				int size = imageList.size();
				for(int i = 0 ; i < size ; i++)
					if(imageList.get(i) != null)
						this.recycleBitmap(imageList.get(i));
			}
		}catch(Exception e){}
		
        super.onDestroy();
        
    }
	
	private void recycleBitmap(ImageView iv) {
		try{
	    	Drawable d = iv.getDrawable();
	    	if (d instanceof BitmapDrawable) {
	    		Bitmap b = ((BitmapDrawable)d).getBitmap();
	    		b.recycle();
	        }	// 현재로서는 BitmapDrawable 이외의 drawable 들에 대한 직접적인 메모리 해제는 불가능하다.
	    	d.setCallback(null);
		}catch(Exception e){}
    	
    }
}